package cmdb

import (
	"fmt"
	"github.com/dghubble/sling"
	"net/http"
	"encoding/json"
)
type QueryRequest struct {
	Query     string   `json:"query,omitempty"`
	Fields     []string   `json:"fields,omitempty"`
}

var httpClient = http.DefaultClient
var base = sling.New().Base(apiURL).Client(httpClient)

const (
	apiURL   string = "http://cmdb.aa.com/api/"
	username string = "bb"
	password string = "aa"
)

func GetToken() string {
	type Params struct {
		Username string `url:"username"`
		Password string `url:"password"`
	}
	params := &Params{username, password}
	response := &CmdbResponse{}
	resp, err := base.New().Get("token").QueryStruct(params).ReceiveSuccess(response)
	fmt.Println(response, resp)
	fmt.Println(response.Result)
	fmt.Println(err)
	aa := response.Result.(string)
	return aa
}

func GetServer(primaryIp string ,serviceTag string, name string, assetsNo string) []ServerDTO {
	query := ""
	if primaryIp !="" {
		query += "&& primaryIp::eq::" +primaryIp
	}
	if serviceTag !="" {
		query += "&& serviceTag::eq::" +serviceTag
	}
	if name !="" {
		query += "&& name::eq::" +name
	}
	if assetsNo !="" {
		query += "&& assetsNo::eq::" +assetsNo
	}
	fmt.Println("query " ,query)
	field:=[]string{"realServiceTag", "realPrimaryIp", "groupName", "appName", "appUk", "productLineName", "operatingSystemType", "operatingSystemName",
					"templateName", "templateDisplayName", "agentOsType", "agentOsName", "assetsNo", "contractNo", "deviceStatus", "purchaseDate", "warrantyDate", "shelvesDate", "shelfDate", "appId", "idcName",
					"roomName", "rackName", "position", "manufacturerName", "deviceModelName", "skuName"}
	body := &QueryRequest{ query,field}
	response := &ServerResponse{}
	resp, err := base.New().Set("x-auth-token",GetToken()).Post("servers/search").BodyJSON(body).ReceiveSuccess(response)
	fmt.Println( resp)
	fmt.Println(err)
	serverDTOs := response.Result

	return serverDTOs
}

func GetVip(ip string) []VIPDTO {
	query := "ip::like::" +ip
	field:=[]string{"idcName", "idcNameAbbr"}
	body := &QueryRequest{ query,field}
	response := &VIPResponse{}
	resp, err := base.New().Set("x-auth-token",GetToken()).Post("virtualIps/search").BodyJSON(body).ReceiveSuccess(response)
	fmt.Println( resp)
	fmt.Println(err)
	vipDTOs := response.Result
	//fmt.Printf("%+v\n", serverDTO)

	res2B, _ := json.Marshal(vipDTOs)
	fmt.Println(string(res2B))
	return vipDTOs
}

